package housing.task2.db_exschange;

import housing.task3.dao.HsAddressDao;
import housing.task3.factory.HsAddressDaoFactory;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

import java.io.*;

/**
 * Exports data from DB to .jsn file
 * <p/>
 * Created by IntelliJ IDEA.
 * User: Linderhof
 * Date: 03.12.2010
 * Time: 15:12:45
 */
public class JsnExportDemo {
    public static void main(String[] args) {
        configureLogger();

        HsAddressDao dao = HsAddressDaoFactory.create();
        JsnExporter exporter = new JsnExporter();
        exporter.export(dao);

        System.out.println("Exported file:\n");
        displayFile(exporter.getDefaultExportFile());
    }

    private static void displayFile(File file) {
        FileReader reader = null;
        BufferedReader in = null;

        try {
            reader = new FileReader(file);
            in = new BufferedReader(reader);
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void configureLogger() {
        final Logger logger = Logger.getRootLogger();
        final String logFilePath =
                ".\\timoshenko_housing\\src\\main\\logs\\JsnExportDemo.log";
        try {
            FileAppender appenderTXT =
                    new FileAppender(new SimpleLayout(), logFilePath);
            logger.addAppender(appenderTXT);
        } catch (IOException ioe) {
            System.out.println("Failed create log file");
        }
    }
}
